<template>
  <div class="container">
    <h1 class="topTitle">GEOJSON层</h1>
    <div style="height: 600px; width: 100%">
      <l-map class="map" ref="map" :options="mapOptions" @ready="doSomethingOnReady()">
         <l-tile-layer :url="mapOptions.url"></l-tile-layer>
        <l-geo-json :geojson="geojson"
                    :options="json_options"
                    :options-style="styleFunction"></l-geo-json>

        <l-control-zoom position="topleft" zoom-in-title="放大" zoom-out-title="缩小"></l-control-zoom>
      </l-map>
    </div>
  </div>
</template>

<script>
  const GEO_SERVER_URL = process.env.GEO_SERVER_URL
  import csv2geojson from "csv2geojson";
  import toGeoJSON from "togeojson";

  export default {
  name: "TileLayerPage",
  components: {
  },
  data() {
    return {
      map:null,
      //地图参数
      mapOptions:{
        attributionControl :false,
        zoomControl:false,
        minZoom: 2,
        maxZoom: 14,
        zoom: 6,
        center: {'lon':116.404,'lat':39.915},
        preferCanvas: true,
        url: 'http://webrd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}',
        attribution:  '&copy; WebGis',
      },
      layers: [
        {
          url:"http://webrd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}",
          name: '底图',
          visible: true,
          format: 'image/png',
          layers: 'nexrad-n0r-900913',
          transparent: false,
          attribution: "图层演示",
          layertype:"base"
        },
        {
          url:"http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r.cgi",
          name: 'WMS图层演示',
          visible: false,
          format: 'image/png',
          layers: 'nexrad-n0r-900913',
          transparent: true,
          attribution: "图层演示",
          layertype:"overlay"
        }
      ],
      geojson: null,
      //主题色
      theme:{
        color:"green",
        theme_textcolor:"theme_green",
        theme_activecolor: "#3bc96a",
      },
      //geojson层
      geolayers: {
        visable:false,
        administrative_regions:{
          geojson:null,
          cfg:{
            layer_name:'',//图层后台名
            source:'省',
            filter_col_name:'',//过滤列名称
            show_col_name:'name'//显示列名称
          },
          style:{
            weight: 2, //轮廓粗细
            color: '#3bc96a', //轮廓颜色
            opacity: 1,//透明度
            fillColor: '#3bc96a', //内部填充的颜色
            fillOpacity: 0.2 //内部填充的透明度
          },
          tpl:{
            tipHtml:"<div>{{GIS_XZ_NAME}}</div>" ,//tip模板html
            popHtml:"<div>弹出：{{GIS_XZ_NAME}}</div>" ,//弹出模板html
          }
        }

      }
    }
  },
  methods: {
    doSomethingOnReady() {
      this.map = this.$refs.map.mapObject
    },
    async showgeojson(data){

      let url = GEO_SERVER_URL + '/China/ows?service=WFS&version=1.0.0&request=GetFeature';
      url+='&maxFeatures=50'
      let format_type = 'geojson'
      if(data.cfg.outformat){
        format_type = data.cfg.outformat
      }
      switch (format_type) {
        case 'geojson' :  url+='&outputFormat='+encodeURIComponent('application/json') ;break;
        case 'csv' :  url+='&outputFormat='+encodeURIComponent('CSV') ;break;
        case 'kml': url+='&outputFormat='+encodeURIComponent('application/vnd.google-earth.kml+xml') ;break;
        case 'gml':
          url+='&outputFormat='+encodeURIComponent('text/xml') ;
          url+='&subtype='+encodeURIComponent('gml/2.1.2') ;break;
      }
      let spec_code = '';
      switch (data.cfg.source) {
        case '省' :
          this.layers.geolayers.administrative_regions.cfg.filter_col_name = data.cfg.source+"代码";
          this.layers.geolayers.administrative_regions.cfg.show_col_name = data.cfg.source;
          this.layers.geolayers.administrative_regions.cfg.layer_name = 'China:sheng';
          break;
        case '市' :
          this.layers.geolayers.administrative_regions.cfg.filter_col_name = data.cfg.source+"代码";
          this.layers.geolayers.administrative_regions.cfg.show_col_name = data.cfg.source;
          this.layers.geolayers.administrative_regions.cfg.layer_name = 'China:shi';
          break;
        case '县' :
          this.layers.geolayers.administrative_regions.cfg.filter_col_name = "PAC";
          this.layers.geolayers.administrative_regions.cfg.show_col_name = "NAME";
          this.layers.geolayers.administrative_regions.cfg.layer_name = 'China:xian';
          break;

      }
      //源地址
      url+='&typeName='+encodeURIComponent(this.layers.geolayers.administrative_regions.cfg.layer_name);
      //过滤器
      url+='&cql_filter='+ encodeURIComponent("\""+this.layers.geolayers.administrative_regions.cfg.filter_col_name+"\"="+data.filter.code);

      this.loadingText = '准备获取数据请稍等';
      console.log(url)
      const response = await fetch(url);

      this.loadingText = '获取完成,准备渲染数据';

      switch (format_type) {
              //geojson已支持
        case 'geojson' : this.layers.geolayers.administrative_regions.geojson = await response.json();;break;
        case 'csv' :
          var csvStr = await response.text();
          var that = this
          //console.log(csvStr);
          var layer = this.layers.geolayers.administrative_regions.geojson;
          var onparse = (function (err,geojson) {
            console.log(geojson);

            that.layers.geolayers.administrative_regions.geojson  = geojson;
            console.log(that.layers.geolayers.administrative_regions.geojson);
          });
          var geoJson1 = csv2geojson.csv2geojson(csvStr, onparse);
          console.log('geoJson1',geoJson1 );
          console.log('geojson',this.layers.geolayers.administrative_regions.geojson );
          //this.layers.geolayers.administrative_regions.geojson = geoJson1 ;
          break;
              //kml已支持
        case 'kml' :
          let xml = (new DOMParser()).parseFromString(await response.text(), 'text/xml');
          this.layers.geolayers.administrative_regions.geojson = toGeoJSON.kml(xml);
          break;
        case 'gml' :
          var gmlStr = await response.text();
          var that = this
          //console.log(csvStr);
          var layer = this.layers.geolayers.administrative_regions.geojson;
          var onparsegml = (function (err,geojson) {
            console.log(geojson);
          });
          var geoJson1 = gmlToGenJson(csvStr, onparsegml);
          //
          break;
              //outputFormat=text/xml; subtype=gml/2.1.2
      }
      this.layers.geolayers.administrative_regions.cfg.source = data.cfg.source;
      this.layers.geolayers.administrative_regions.style = data.style;
      this.layers.geolayers.administrative_regions.tpl.tipHtml = data.tpl.tipHtml;
      this.layers.geolayers.administrative_regions.tpl.popHtml = data.tpl.popHtml;
      console.log('geojson',this.layers.geolayers.administrative_regions.geojson );
      this.loadingText = '';
    },
  },
  computed: {
    json_options() {
      return {
        onEachFeature: this.onEachFeatureFunction
      };
    },
    styleFunction() {
      const fillColor = this.theme.theme_activecolor; // important! need touch fillColor in computed for re-calculate when change fillColor
      const that = this;
      return () => {
        return  that.geolayers.administrative_regions.style;
      };
    },
    onEachFeatureFunction() {
      return (feature, layer) => {

        console.log(feature,layer);
        /*L.circleMarker(layer.getLatLng(), {
          radius: 8,
          fillColor: "#ff7800",
          color: "#000",
          weight: 1,
          opacity: 1,
          fillOpacity: 0.8
        });*/
        /*var shieldIcon = L.icon({
            iconUrl: '/static/marker-shield.png',
            iconSize: [40, 40],
            iconAnchor: [20, 40],
            popupAnchor: [-3, -76],
            //shadowUrl: 'my-icon-shadow.png',
            shadowSize: [68, 95],
            shadowAnchor: [22, 94]
        });*/

        //layer.setIcon(shieldIcon);
        //console.log('feature',feature);
        //console.log('layer',layer);
        //console.log('this',this.layers.geolayers.administrative_regions.cfg.source);

        let in_text = feature.properties[this.geolayers.administrative_regions.cfg.show_col_name];
        //tip值
        let tipText = this.geolayers.administrative_regions.tpl.tipHtml.replaceAll("{{GIS_XZ_NAME}}", in_text);//替换行政区域

        //弹出值
        let popText = this.geolayers.administrative_regions.tpl.popHtml.replaceAll("{{GIS_XZ_NAME}}", in_text);//替换行政区域
        if(tipText!=''){
          layer.bindTooltip(
                  tipText,
                  { permanent: false, sticky: true }
          );
        }
        if(popText!=''){
          layer.bindPopup(popText).openPopup();
        }


      };
    }
  },
  async created () {
    /**
     * 测试地址
     * http://datav.aliyun.com/tools/atlas/index.html#&lat=26.773813330666446&lng=106.70059204101562&zoom=9
     * **/
    const response = await fetch('https://geo.datav.aliyun.com/areas_v3/bound/370000_full.json');
    this.geojson = await response.json();
  },
}
</script>

<style lang="stylus" scoped>
.container
  width: 100%
  h1.topTitle
    text-align: center
</style>